package com.bskj.kuaifu.filter;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.UserCar;
import com.bskj.common.bean.model.UserInfo;
import com.bskj.common.bean.model.UserThirdAuth;
import com.bskj.common.constants.CommonConstatns;
import com.bskj.common.utils.JSONUtil;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.StringUtils;
import com.bskj.kuaifu.service.IUserInfoService;
import com.bskj.kuaifu.service.IUserThirdAuthService;

public class SessionFilter implements MyFilter {
	private MyFilter next;

	private Set<String> prefixIignores = new HashSet<String>();

	private IUserInfoService userInfoService;

	private IUserThirdAuthService userThirdAuthService;

	public FilterConfig config;

	public IUserInfoService getUserInfoService() {
		return userInfoService;
	}

	public void setUserInfoService(IUserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	public IUserThirdAuthService getUserThirdAuthService() {
		return userThirdAuthService;
	}

	public void setUserThirdAuthService(IUserThirdAuthService userThirdAuthService) {
		this.userThirdAuthService = userThirdAuthService;
	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		if (canIgnore(request)) {
			if (next != null) {
				next.doFilter(request, response, chain);
			} else {
				chain.doFilter(request, response);
			}
			return;
		}

		LogUtils.debug("url:" + request.getRequestURI());
		Map<String, Object> extraParams = new HashMap<String, Object>();
		LogUtils.debug(JSONObject.toJSONString(request.getParameterMap()));
		String userId = request.getParameter("userId");
		UserInfo userInfo = null;
		List<UserCar> userCars = null;
		try {

			/*
			 * 从公众号进入页面：
			 * 1、如果openid和appid找不到对应用户，保存该用户，如果该用户存在，但是没有unionid（老数据），更新unionid
			 * 2、根据userId去t_user_third_auth 找对应的小程序openid，如果没有找到，跳转到小程序
			 * 3、如果找到了对应的小程序的openid,查询用户车牌绑定情况，并更新用户车牌信息
			 */
			// step1 更新或者新增userInfo
			JSONObject jsonUser = JSONUtil.getJSONFromString(request.getParameter("jsonWechatUser"));

			/*
			 * 判断是否关注公众号 ，没有关注需要关注才能使用
			 */
			// Object subscribeOB= jsonUser.get("subscribe");
			// if(subscribeOB !=null){
			// String subscribe= jsonUser.get("subscribe").toString();
			// if("0".equals(subscribe)){
			// request.getRequestDispatcher("/user/nono").forward(request,
			// response);
			// return;
			// }
			// }

			if (StringUtils.isBank(userId)) {
				
				if (jsonUser.get("unionid") != null) {
					String unionid = jsonUser.get("unionid").toString();
					userInfo = userInfoService.getUserInfoByUnionidId(unionid);
					if (userInfo != null) {
						if (StringUtils.isBank(userInfo.getOpenid())) {
							userInfo.setAppId(request.getParameter("appId"));
							userInfo.setOpenId(request.getParameter("openId"));
							userInfo.setName((String) jsonUser.get("nickname"));
							userInfo.setImage((String) jsonUser.get("headimgurl"));
							userInfo.setUpdateTime(new Date());
							userInfoService.update(userInfo);
						}
					}else {
						userInfo = new UserInfo();
						userInfo = userInfoService.getUserInfoByOpenId(request.getParameter("openId"));
						if(userInfo != null){
							if(StringUtils.isBank(userInfo.getUnionid())){
								userInfo.setAppId(request.getParameter("appId"));
								userInfo.setUnionid(unionid);
								userInfo.setName((String) jsonUser.get("nickname"));
								userInfo.setImage((String) jsonUser.get("headimgurl"));
								userInfo.setUpdateTime(new Date());
								userInfoService.update(userInfo);
							}
						}else {
							userInfo = new UserInfo();
							userInfo.setName((String) jsonUser.get("nickname"));
							userInfo.setImage((String) jsonUser.get("headimgurl"));
							userInfo.setUnionid(unionid);
							userInfo.setAppId(request.getParameter("appId"));
							userInfo.setOpenId(request.getParameter("openId"));
							userInfo.setCreateTime(new Date());
							userInfo.setUpdateTime(new Date());
						}
					}
				} else {
					userInfo = userInfoService.getUserInfoByOpenId(request.getParameter("openId"));
					if(userInfo != null){
						if(StringUtils.isBank(userInfo.getUnionid())){
							userInfo.setAppId(request.getParameter("appId"));
							userInfo.setName((String) jsonUser.get("nickname"));
							userInfo.setImage((String) jsonUser.get("headimgurl"));
							userInfo.setUpdateTime(new Date());
							userInfoService.update(userInfo);
						}
					}else {
						userInfo = new UserInfo();
						userInfo.setName((String) jsonUser.get("nickname"));
						userInfo.setImage((String) jsonUser.get("headimgurl"));
						userInfo.setAppId(request.getParameter("appId"));
						userInfo.setOpenId(request.getParameter("openId"));
						userInfo.setCreateTime(new Date());
						userInfo.setUpdateTime(new Date());
					}
				}
			} else {
				userInfo = userInfoService.get(Integer.parseInt(userId));
			}

			if (userInfo != null && StringUtils.isBank(userId)) {
				// step 2 根据userId去t_user_third_auth 找对应的小程序openid
				UserThirdAuth thirdAuth = userThirdAuthService.getUserThirdAuth(userInfo.getId(),
						CommonConstatns.KUAIFU_WX_SMALL_APP_APPID);

				// step3
				if (thirdAuth != null) {
					userInfoService.queryUserNoSenseStatus(userInfo.getId(), thirdAuth.getOpenid(), "");
				}
			}
			userCars = userInfoService.getMyCarNo(userInfo.getId());

			LogUtils.debug(JSONObject.toJSONString(userInfo));
			if (userInfo != null && !(userCars == null || userCars.size() == 0)) {
				extraParams.put("userId", userInfo.getId());
				extraParams.put("image", userInfo.getImage());
				RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(request, extraParams);
				if (next != null) {
					next.doFilter(requestParameterWrapper, response, chain);
				} else {
					chain.doFilter(requestParameterWrapper, response);
				}
				return;
			} else {
				if (userInfo != null) {
					request.setAttribute("userId", userInfo.getId());
					
				}
				chain.doFilter(request, response);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void destroy() {
		config = null;
		prefixIignores = null;
	}

	private boolean canIgnore(HttpServletRequest request) {
		String url = request.getParameter("uri");
		if (StringUtils.isBank(url)) {
			return false;
		}
		for (String ignore : prefixIignores) {
			if (url.startsWith(ignore)) {
				return true;
			}
		}
		return false;
	}

	public Set<String> getPrefixIignores() {
		return prefixIignores;
	}

	public void setPrefixIignores(Set<String> prefixIignores) {
		this.prefixIignores = prefixIignores;
	}

	public MyFilter next() {
		return next;
	}

	public void setNext(MyFilter myFitler) {
		this.next = myFitler;
	}
}
